package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.IOException;

@Controller // 要返回页面。 @RestController 不能使用它
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    // www.gmall.com/  或 www.gmall.com/index.html Thymeleaf 如何存储数据.
    @GetMapping({"/","index.html"})
    public String index(Model model, HttpServletRequest request){
        Result result = this.productFeignClient.getBaseCategoryList();
        //  返回数据. 后台要存储 ${list}
        //  request.setAttribute("list",result.getData());
        model.addAttribute("list",result.getData());
        return "index/index";
    }

    //  使用 nginx 做静态化：
    //  创建首页静态化模板. 将后台的首页分类数据，直接写死到页面上.
    @GetMapping("create/index")
    @ResponseBody
    public Result createIndex(){
        //  创建一个对象。IContext
        //  public final void process(String template, Set<String> templateSelectors, IContext context, Writer writer) {
        Context context = new Context();
        //  name=模板引擎需要获取到的key     value= key 所对应的值.
        Result result = this.productFeignClient.getBaseCategoryList();
        context.setVariable("list",result.getData());
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("F:\\index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  调用模板引擎
        this.templateEngine.process("index/index.html",context,fileWriter);
        //  返回OK.
        return Result.ok();
    }


}
